<template>
  <div class="p-4">
    <el-card>
      <div class="flex justify-between items-center mb-4">
        <el-button type="primary" @click="openDialog()">新增</el-button>
      </div>

      <el-table :data="techStacks" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="名称" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="openDialog(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" title="技术栈">
      <el-form :model="form" label-width="80px">
        <el-form-item label="名称">
          <el-input v-model="form.name" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { getTechStacks, addTechStack, updateTechStack, deleteTechStack } from '@/api/techstack'
import { ElMessage, ElMessageBox } from 'element-plus'

const techStacks = ref([])
const dialogVisible = ref(false)
const form = ref({
  id: null,
  name: ''
})

const fetchData = async () => {
  const res = await getTechStacks()
  if (res.code === 0) {
    techStacks.value = res.data
  }
}

const openDialog = (item = null) => {
  if (item) {
    form.value = { ...item }
  } else {
    form.value = { id: null, name: '' }
  }
  dialogVisible.value = true
}

const handleSubmit = async () => {
  const { id, name } = form.value
  if (!name) return ElMessage.warning('请输入名称')

  const res = id ? await updateTechStack(id, { name }) : await addTechStack({ name })
  if (res.code === 0) {
    ElMessage.success(id ? '更新成功' : '添加成功')
    dialogVisible.value = false
    fetchData()
  } else {
    ElMessage.error(res.msg || '操作失败')
  }
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定要删除吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    const res = await deleteTechStack(id)
    if (res.code === 0) {
      ElMessage.success('删除成功')
      fetchData()
    } else {
      ElMessage.error(res.msg || '删除失败')
    }
  }).catch(() => {})
}

onMounted(() => {
  fetchData()
})
</script>
